<template>
    <v-dialog v-model="dialogVisible" max-width="800px" scrollable>
        <v-card class="elevation-10">
            <!-- 头部 -->
            <v-card-title class="d-flex align-center pa-4 bg-primary text-white">
                <v-icon color="white" class="mr-3" size="28">mdi-account-group</v-icon>
                <span class="text-h5 font-weight-bold">客户关系详情</span>
                <v-spacer />
                <v-btn icon variant="text" @click="close" color="white" size="large">
                    <v-icon>mdi-close</v-icon>
                </v-btn>
            </v-card-title>

            <!-- 主要内容 -->
            <v-card-text class="pa-6">
                <!-- 基础关系信息 -->
                <v-card class="elevation-9 mb-4">
                    <v-card-title class="bg-blue-grey-lighten-5 text-primary d-flex align-center">
                        <v-icon class="mr-2" color="primary">mdi-account-network</v-icon>
                        关系基础信息
                    </v-card-title>
                    <v-card-text class="pa-4">
                        <v-row dense>
                            <v-col cols="12" md="4">
                                <div class="info-item">
                                    <v-icon class="mr-3" color="primary">mdi-family-tree</v-icon>
                                    <div>
                                        <div class="info-label">关系类型</div>
                                        <v-chip :color="getDictColor(detail.relationType, 'relation_type')" size="small"
                                            variant="flat">
                                            {{ getDictLabel(detail.relationType, 'relation_type') }}
                                        </v-chip>
                                    </div>
                                </div>
                            </v-col>
                            <v-col cols="12" md="4">
                                <div class="info-item">
                                    <v-icon class="mr-3" color="primary">mdi-star</v-icon>
                                    <div>
                                        <div class="info-label">主要联系人</div>
                                        <v-chip :color="detail.isPrimary === '1' ? 'success' : 'grey'" size="small"
                                            variant="flat">
                                            {{ detail.isPrimary === '1' ? '是' : '否' }}
                                        </v-chip>
                                    </div>
                                </div>
                            </v-col>
                            <v-col cols="12" md="4">
                                <div class="info-item">
                                    <v-icon class="mr-3" color="primary">mdi-source-branch</v-icon>
                                    <div>
                                        <div class="info-label">来源渠道</div>
                                        <div class="info-value">
                                            <v-chip v-if="detail.sourceChannel" color="info" size="small"
                                                variant="outlined">
                                                {{ getChannelNameByIdSync(detail.sourceChannel) }}
                                            </v-chip>
                                            <span v-else class="text-grey">未设置</span>
                                        </div>
                                    </div>
                                </div>
                            </v-col>
                            <v-col cols="12" md="4">
                                <div class="info-item">
                                    <v-icon class="mr-3" color="primary">mdi-clock</v-icon>
                                    <div>
                                        <div class="info-label">创建时间</div>
                                        <div class="info-value">{{ formatDate(detail.createTime) }}</div>
                                    </div>
                                </div>
                            </v-col>
                            <v-col cols="12" md="4">
                                <div class="info-item">
                                    <v-icon class="mr-3" color="primary">mdi-account</v-icon>
                                    <div>
                                        <div class="info-label">创建者</div>
                                        <div class="info-value">{{ detail.createBy || '系统' }}</div>
                                    </div>
                                </div>
                            </v-col>
                            <v-col cols="12" md="4">
                                <div class="info-item">
                                    <v-icon class="mr-3" color="primary">mdi-priority-high</v-icon>
                                    <div>
                                        <div class="info-label">优先级</div>
                                        <div class="info-value">{{ detail.priority || '普通' }}</div>
                                    </div>
                                </div>
                            </v-col>
                            <v-col cols="12" v-if="detail.remark">
                                <div class="info-item">
                                    <v-icon class="mr-3" color="primary">mdi-note-text</v-icon>
                                    <div>
                                        <div class="info-label">备注</div>
                                        <div class="info-value">{{ detail.remark }}</div>
                                    </div>
                                </div>
                            </v-col>
                        </v-row>
                    </v-card-text>
                </v-card>

                <v-row>
                    <!-- 家长信息 -->
                    <v-col cols="12" md="6">
                        <v-card class="elevation-9 h-100">
                            <v-card-title class="bg-blue-lighten-5 text-primary d-flex align-center">
                                <v-icon class="mr-2" color="primary">mdi-account</v-icon>
                                家长信息
                            </v-card-title>
                            <v-card-text class="pa-4">
                                <div v-if="detail.customer?.name">
                                    <div class="profile-header">
                                        <v-avatar size="60" color="primary" class="customer-avatar">
                                            <v-img v-if="detail.customer?.avatar" :src="detail.customer.avatar" />
                                            <span v-else class="text-h4 text-white">{{ detail.customer?.name?.charAt(0)
                                                }}</span>
                                        </v-avatar>
                                        <div class="profile-info">
                                            <h3 class="profile-name">{{ detail.customer?.name }}</h3>
                                            <div class="profile-tags">
                                                <v-chip v-if="detail.customer?.gender"
                                                    :color="getDictColor(detail.customer?.gender, 'customer_sex')"
                                                    size="small" variant="flat" class="mr-2">
                                                    {{ getDictLabel(detail.customer?.gender, 'customer_sex') }}
                                                </v-chip>
                                                <v-chip v-if="detail.customer?.status"
                                                    :color="getDictColor(detail.customer?.status, 'customer_status')"
                                                    size="small" variant="outlined">
                                                    {{ getDictLabel(detail.customer?.status, 'customer_status') }}
                                                </v-chip>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="contact-info mt-4">
                                        <div v-if="detail.customer?.phone" class="contact-item">
                                            <v-icon class="contact-icon" color="primary">mdi-phone</v-icon>
                                            <span class="contact-text">{{ detail.customer?.phone }}</span>
                                            <v-btn icon="mdi-content-copy" size="small" variant="text"
                                                @click="copyToClipboard(detail.customer?.phone)" class="copy-btn">
                                            </v-btn>
                                        </div>
                                        <div v-if="detail.customer?.email" class="contact-item">
                                            <v-icon class="contact-icon" color="primary">mdi-email</v-icon>
                                            <span class="contact-text">{{ detail.customer?.email }}</span>
                                            <v-btn icon="mdi-content-copy" size="small" variant="text"
                                                @click="copyToClipboard(detail.customer?.email)" class="copy-btn">
                                            </v-btn>
                                        </div>
                                        <div v-if="detail.customer?.idCard" class="contact-item">
                                            <v-icon class="contact-icon"
                                                color="primary">mdi-card-account-details</v-icon>
                                            <span class="contact-text">{{ maskIdCard(detail.customer?.idCard) }}</span>
                                        </div>
                                        <div v-if="detail.customer?.address" class="contact-item">
                                            <v-icon class="contact-icon" color="primary">mdi-map-marker</v-icon>
                                            <span class="contact-text">{{ detail.customer?.address }}</span>
                                        </div>
                                        <div v-if="detail.customer?.remark" class="contact-item">
                                            <v-icon class="contact-icon" color="primary">mdi-note-text</v-icon>
                                            <span class="contact-text">{{ detail.customer?.remark }}</span>
                                        </div>
                                    </div>
                                </div>

                                <div v-else class="empty-state">
                                    <v-icon size="64" color="grey-lighten-2">mdi-account-off</v-icon>
                                    <div class="empty-title">暂无家长信息</div>
                                </div>
                            </v-card-text>
                        </v-card>
                    </v-col>

                    <!-- 学生信息 -->
                    <v-col cols="12" md="6">
                        <v-card class="elevation-9 h-100">
                            <v-card-title class="bg-green-lighten-5 text-success d-flex align-center">
                                <v-icon class="mr-2" color="success">mdi-school</v-icon>
                                学生信息
                                <v-spacer />
                                <v-chip color="success" variant="outlined" size="small">
                                    {{ detail.students?.length || 0 }}名学生
                                </v-chip>
                            </v-card-title>
                            <v-card-text class="pa-4">
                                <div v-if="detail.students && detail.students.length > 0" class="students-list">
                                    <div v-for="(student, index) in detail.students" :key="student.id || index"
                                        class="student-item hover-card" :class="{ 'primary-student': index === 0 }">
                                        <div class="student-header">
                                            <v-avatar size="60" :color="index === 0 ? 'success' : 'secondary'"
                                                class="student-avatar">
                                                <v-img v-if="student.avatar" :src="student.avatar" />
                                                <span v-else class="text-h5 text-white">{{ student.name?.charAt(0) ||
                                                    '学' }}</span>
                                            </v-avatar>
                                            <div class="student-info">
                                                <div class="student-name">
                                                    {{ student.name || '未命名' }}
                                                    <v-chip v-if="index === 0" color="success" size="x-small"
                                                        variant="flat" class="ml-2">
                                                        主要
                                                    </v-chip>
                                                </div>
                                                <div class="student-tags">
                                                    <v-chip v-if="student.gender"
                                                        :color="getDictColor(student.gender, 'customer_sex')"
                                                        size="x-small" variant="flat" class="mr-1">
                                                        {{ getDictLabel(student.gender, 'customer_sex') }}
                                                    </v-chip>
                                                    <v-chip v-if="student.grade"
                                                        :color="getDictColor(student.grade, 'student_grade')"
                                                        size="x-small" variant="outlined">
                                                        {{ getDictLabel(student.grade, 'student_grade') }}
                                                    </v-chip>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="student-details">
                                            <div v-if="student.birthDate" class="detail-item">
                                                <v-icon size="14" color="success">mdi-calendar</v-icon>
                                                <span>{{ formatDate(student.birthDate) }} ({{
                                                    calculateAge(student.birthDate) }}岁)</span>
                                            </div>
                                            <div v-if="student.school" class="detail-item">
                                                <v-icon size="14" color="success">mdi-school</v-icon>
                                                <span>{{ student.school }}</span>
                                            </div>
                                            <div v-if="student.className" class="detail-item">
                                                <v-icon size="14" color="success">mdi-google-classroom</v-icon>
                                                <span>{{ student.className }}</span>
                                            </div>
                                            <div v-if="student.educationType" class="detail-item">
                                                <v-icon size="14" color="success">mdi-book-education</v-icon>
                                                <v-chip
                                                    :color="getDictColor(student.educationType, 'student_education_type')"
                                                    size="x-small" variant="flat">
                                                    {{ getDictLabel(student.educationType, 'student_education_type') }}
                                                </v-chip>
                                            </div>
                                            <div v-if="student.status" class="detail-item">
                                                <v-icon size="14" color="success">mdi-progress-check</v-icon>
                                                <v-chip :color="getDictColor(student.status, 'student_status')"
                                                    size="x-small" variant="flat">
                                                    {{ getDictLabel(student.status, 'student_status') }}
                                                </v-chip>
                                            </div>
                                            <div v-if="student.healthInfo" class="detail-item">
                                                <v-icon size="14" color="success">mdi-heart-pulse</v-icon>
                                                <span>{{ student.healthInfo }}</span>
                                            </div>
                                            <div v-if="student.specialNeeds" class="detail-item">
                                                <v-icon size="14" color="success">mdi-star-four-points</v-icon>
                                                <span>{{ student.specialNeeds }}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div v-else class="empty-state">
                                    <v-icon size="64" color="grey-lighten-2">mdi-account-off</v-icon>
                                    <div class="empty-title">暂无学生信息</div>
                                    <div class="empty-subtitle">此客户关系暂未关联学生</div>
                                </div>
                            </v-card-text>
                        </v-card>
                    </v-col>
                </v-row>
            </v-card-text>

            <!-- 底部操作 -->
            <v-card-actions class="px-6 pb-4">
                <v-spacer />
                <v-btn color="grey-darken-1" variant="outlined" @click="close" size="large">
                    关闭
                </v-btn>
                <v-btn color="primary" variant="flat" @click="editRecord" prepend-icon="mdi-pencil" size="large">
                    编辑
                </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import type { CustomerStudentRelationModel } from '@/api/customer/customerrelation/CustomerStudentRelationManagementApi';
import { getDictListSync } from '@/utils/dict';
import { getChannelListSync, getChannelNameByIdSync } from '@/utils/channel';
import { useMessage } from '@/composables/useMessage';

const { success: showSuccess } = useMessage();

// 基础数据
const dialogVisible = ref(false);
const detail = reactive<CustomerStudentRelationModel>({
    students: [],
    customer: {}
});

// 字典数据
const dict = reactive({
    'relation_type': [] as any[],
    'customer_sex': [] as any[],
    'customer_type': [] as any[],
    'customer_status': [] as any[],
    'student_grade': [] as any[],
    'student_status': [] as any[],
    'student_education_type': [] as any[],
});

// 事件发射
const emit = defineEmits<{
    edit: [record: CustomerStudentRelationModel];
}>();

// 显示详情对话框
function showDetail(record: CustomerStudentRelationModel) {
    Object.assign(detail, record);
    dialogVisible.value = true;
}

// 关闭对话框
function close() {
    dialogVisible.value = false;
    // 清空数据
    Object.keys(detail).forEach(key => {
        delete detail[key as keyof CustomerStudentRelationModel];
    });
}

// 编辑记录
function editRecord() {
    emit('edit', detail);
    close();
}

// 复制到剪贴板
async function copyToClipboard(text: string) {
    try {
        await navigator.clipboard.writeText(text);
        showSuccess('已复制到剪贴板');
    } catch (error) {
        console.error('复制失败:', error);
    }
}

// 脱敏身份证号
function maskIdCard(idCard: string): string {
    if (!idCard || idCard.length < 8) return idCard;
    return idCard.substring(0, 4) + '****' + idCard.substring(idCard.length - 4);
}

// 格式化日期
function formatDate(date: Date | undefined): string {
    if (!date) return '-';
    return new Date(date).toLocaleDateString('zh-CN');
}

// 计算年龄
function calculateAge(birthDate: Date | undefined): number {
    if (!birthDate) return 0;
    const today = new Date();
    const birth = new Date(birthDate);
    let age = today.getFullYear() - birth.getFullYear();
    const monthDiff = today.getMonth() - birth.getMonth();
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
        age--;
    }
    return age;
}

// 字典工具函数
function getDictLabel(value: any, dictType: string): string {
    const dictList = dict[dictType as keyof typeof dict] as any[];
    const item = dictList?.find(item => item.dictValue === value);
    return item?.dictName || value;
}

function getDictColor(value: any, dictType: string): string {
    const colors = ['primary', 'success', 'warning', 'error', 'info', 'purple', 'pink', 'indigo'];
    const dictList = dict[dictType as keyof typeof dict] as any[];
    const index = dictList?.findIndex(item => item.dictValue === value) || 0;
    return colors[index % colors.length];
}

// 初始化字典数据
function initDict() {
    dict['relation_type'] = getDictListSync('relation_type') || [];
    dict['customer_sex'] = getDictListSync('customer_sex') || [];
    dict['customer_type'] = getDictListSync('customer_type') || [];
    dict['customer_status'] = getDictListSync('customer_status') || [];
    dict['student_grade'] = getDictListSync('student_grade') || [];
    dict['student_status'] = getDictListSync('student_status') || [];
    dict['student_education_type'] = getDictListSync('student_education_type') || [];
}

// 初始化
initDict();

// 暴露方法
defineExpose({
    showDetail
});
</script>

<style lang="scss" scoped>
// 信息项样式
.info-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 12px;
    padding: 8px;
    transition: all 0.2s ease;

    &:hover {
        background: rgba(0, 0, 0, 0.02);
        border-radius: 8px;
    }

    .v-icon {
        margin-top: 2px;
        flex-shrink: 0;
    }
}

.info-label {
    font-size: 0.75rem;
    font-weight: 600;
    color: #64748b;
    margin-bottom: 4px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.info-value {
    font-size: 0.9rem;
    color: #334155;
    font-weight: 500;
}

// 客户档案头部
.profile-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px;
    background: rgba(0, 0, 0, 0.02);
    border-radius: 12px;
}

.customer-avatar {
    margin-right: 16px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.profile-info {
    flex: 1;
}

.profile-name {
    font-size: 1.3rem;
    font-weight: 700;
    color: #1a202c;
    margin-bottom: 8px;
}

.profile-tags {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

// 联系信息
.contact-info {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.contact-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background: rgba(0, 0, 0, 0.02);
    border-radius: 8px;
    transition: all 0.2s ease;

    &:hover {
        background: rgba(0, 0, 0, 0.04);
        transform: translateX(2px);
    }
}

.contact-icon {
    margin-right: 12px;
    flex-shrink: 0;
}

.contact-text {
    flex: 1;
    font-weight: 500;
    color: #374151;
}

.copy-btn {
    opacity: 0.6;
    transition: opacity 0.2s ease;

    &:hover {
        opacity: 1;
    }
}

// 学生列表
.students-list {
    max-height: 500px;
    overflow-y: auto;

    &::-webkit-scrollbar {
        width: 6px;
    }

    &::-webkit-scrollbar-track {
        background: rgba(0, 0, 0, 0.05);
        border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
        background: rgba(0, 0, 0, 0.2);
        border-radius: 3px;

        &:hover {
            background: rgba(0, 0, 0, 0.3);
        }
    }
}

// 学生项
.student-item {
    background: rgba(0, 0, 0, 0.02);
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    border: 1px solid rgba(0, 0, 0, 0.05);
    transition: all 0.2s ease;

    &.primary-student {
        background: rgba(76, 175, 80, 0.05);
        border-color: rgba(76, 175, 80, 0.2);
    }
}

.student-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.student-avatar {
    margin-right: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.student-info {
    flex: 1;
}

.student-name {
    font-size: 1.1rem;
    font-weight: 600;
    color: #1a202c;
    margin-bottom: 6px;
    display: flex;
    align-items: center;
}

.student-tags {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
}

.student-details {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.detail-item {
    display: flex;
    align-items: center;
    padding: 6px 8px;
    background: rgba(255, 255, 255, 0.6);
    border-radius: 6px;
    font-size: 0.85rem;

    .v-icon {
        margin-right: 8px;
        flex-shrink: 0;
    }
}

// 空状态
.empty-state {
    text-align: center;
    padding: 40px 20px;

    .empty-title {
        font-size: 1.1rem;
        font-weight: 600;
        color: #64748b;
        margin-top: 16px;
    }

    .empty-subtitle {
        font-size: 0.9rem;
        color: #94a3b8;
        margin-top: 8px;
    }
}

// 卡片样式，与index.vue保持一致
.v-card {
    &.h-100 {
        height: 100%;
    }

    .v-card-title {
        font-size: 1.1rem;
        font-weight: 600;
        padding: 16px;

        &.bg-primary {
            background: rgb(var(--v-theme-primary)) !important;
        }

        &.bg-blue-grey-lighten-5 {
            background: rgb(var(--v-theme-blue-grey-lighten-5)) !important;
        }

        &.bg-blue-lighten-5 {
            background: rgb(var(--v-theme-blue-lighten-5)) !important;
        }

        &.bg-green-lighten-5 {
            background: rgb(var(--v-theme-green-lighten-5)) !important;
        }

        .v-icon {
            color: inherit !important;
        }
    }
}

// 响应式设计
@media (max-width: 960px) {
    .profile-header {
        flex-direction: column;
        text-align: center;

        .customer-avatar {
            margin-right: 0;
            margin-bottom: 12px;
        }
    }

    .student-header {
        flex-direction: column;
        text-align: center;

        .student-avatar {
            margin-right: 0;
            margin-bottom: 8px;
        }
    }
}

@media (max-width: 600px) {
    .v-card-actions {
        .v-btn {
            flex: 1;
        }
    }
}
</style>